package com.atguigu.gulimall.cart.service.imple;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 购物车
 *
 * @author LaiSanShan
 * @date 2021-08-27
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor threadPool;

    private final String CART_PREFIX = "gulimall:cart:";

    /**
     * 添加到购物车
     *
     * @param skuId 商品id
     * @param num   商品数量
     * @return 商品项
     */
    @Override
    public Cart.CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        // 1.获取当前用户的购物车操作
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String o = (String) cartOps.get(skuId.toString());
        if (StringUtils.isNotBlank(o)) {
            // 添加已有商品到购物车
            Cart.CartItem cartItem = JSON.parseObject(o, Cart.CartItem.class);
            // 叠加商品数量
            cartItem.setCount(cartItem.getCount() + num);
            String jsonString = JSON.toJSONString(cartItem);
            // 更新redis中购物车
            cartOps.put(skuId.toString(), jsonString);
            return cartItem;
        } else {
            // 添加新商品到购物车
            Cart.CartItem cartItem = new Cart.CartItem();
            // 2.远程查询商品详情
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                R r = productFeignService.getSkuInfo(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });
                    // 将商品添加到购物车
                    cartItem.setCheck(true);
                    cartItem.setCount(num);
                    cartItem.setImage(skuInfo.getSkuDefaultImg());
                    cartItem.setTitle(skuInfo.getSkuTitle());
                    cartItem.setSkuId(skuId);
                    cartItem.setPrice(skuInfo.getPrice());
                }
            }, threadPool);

            // 3.远程查询sku的组合信息
            CompletableFuture<Void> getSkuSaleAttrTask = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValues = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(skuSaleAttrValues);
            }, threadPool);

            // 4.全部查询完成，更新redis中的购物车
            CompletableFuture<Void> allTask = CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrTask);
            allTask.get();
            String jsonString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), jsonString);

            return cartItem;
        }
    }

    /**
     * 查询添加商品的购物项
     *
     * @param skuId 商品id
     * @return 商品的购物项
     */
    @Override
    public Cart.CartItem getCartItem(Long skuId) {
        // 1.获取当前用户的购物车操作
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String o = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(o, Cart.CartItem.class);
    }

    /**
     * 获取购物车
     *
     * @return 购物车
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        Cart cartVo = new Cart();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            //1、登录
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            //临时购物车的键
            String temptCartKey = CART_PREFIX + userInfoTo.getUserKey();

            //2、如果临时购物车的数据还未进行合并
            List<Cart.CartItem> tempCartItems = getCartItems(temptCartKey);
            if (tempCartItems != null) {
                //临时购物车有数据需要进行合并操作
                for (Cart.CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                //清除临时购物车的数据
                clearCartInfo(temptCartKey);
            }

            //3、获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<Cart.CartItem> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);

        } else {
            //没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车里面的所有购物项
            List<Cart.CartItem> cartItems = getCartItems(cartKey);
            cartVo.setItems(cartItems);
        }

        return cartVo;
    }

    /**
     * 从redis中删除指定购物车键的数据
     *
     * @param cartKey 购物车键
     */
    @Override
    public void clearCartInfo(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    /**
     * 购物项被选中
     *
     * @param skuId 商品
     * @param check 是否选中
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        Cart.CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), jsonString);
    }

    /**
     * 改变购物项数量
     *
     * @param skuId 商品id
     * @param num   商品数量
     */
    @Override
    public void changeItemCount(Long skuId, Integer num) {
        Cart.CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), jsonString);
    }

    /**
     * 删除购物项
     *
     * @param skuId 商品id
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取登录用户的选中购物项
     *
     * @return 用户的选中购物项
     */
    @Override
    public List<Cart.CartItem> getCurrentUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            //登录购物车键
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            return getCartItems(cartKey).stream()
                    .filter(Cart.CartItem::getCheck)
                    // 获取商品最新价格
                    .peek(item -> item.setPrice(productFeignService.getPrice(item.getSkuId())))
                    .collect(Collectors.toList());
        }
    }

    /**
     * 获取指定购物车键的所有购物项
     *
     * @param cartKey 购物车键
     * @return 所有购物项
     */
    private List<Cart.CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        List<Object> values = operations.values();
        if (!CollectionUtils.isEmpty(values)) {
            return values.stream().map(item -> {
                String toString = (String) item;
                return JSON.parseObject(toString, Cart.CartItem.class);
            }).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    /**
     * 获取购物车的redis操作
     *
     * @return redis操作
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        // 获取当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey;
        if (userInfoTo.getUserId() != null) {
            // 已登录
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            // 未登录
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        // 绑定key的操作
        return redisTemplate.boundHashOps(cartKey);
    }

}
